import Pluto,struct,os,fnmatch,codecs

class Pack:
        """pack the file to bin"""

        def pack(self,tar_dir):
                self.tar_dir=tar_dir
                fl=Pluto.walk(self.tar_dir)
                num=len(fl)
                tar=open(self.tar_dir+'.bin','wb')
                tar.seek(num*8)
                index=[]
                for fn in fl:
                        if fnmatch.fnmatch(fn,'*.bin'):
                                continue
                        offset=tar.tell()
                        index.append(offset)
                        fp=open(fn,'rb')
                        head=fp.read(2)
                        fp.close()
                        if head!='\xff\xfe':
                                print fn,'code is not unicode!'
                                continue
                        fp1=codecs.open(fn,'rb','utf16')
                        text=fp1.read()
                        fp1.close()
                        fp2=codecs.open(fn+'.bin','wb','utf8')
                        fp2.write(text)
                        fp2.close()

                        os.system('agblz z %s %s'%(fn+'.bin',fn+'.bin'))

                        fp3=open(fn+'.bin','rb')
                        data=fp3.read()
                        size=len(data)
                        index.append(size)
                        tar.write(data)
                tar.seek(0)
                for item in index:
                        tar.write(struct.pack('i',item))
                tar.close()
                        
txt2bin=Pack()
txt2bin.pack('text')
txt2bin.pack('txtEvent')
